package com.voodoo.lib_http.builder;

import android.net.Uri;

import com.voodoo.lib_http.request.GetRequest;
import com.voodoo.lib_http.request.RequestCall;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * Author: voodoo
 * CreateDate: 2021/05/29
 * Description:
 */
public class GetBuilder extends OkHttpRequestBuilder<GetBuilder> implements HasParamsable{

    @Override
    public RequestCall build() {
        if (params != null) {
            url = appendParams(url, params);
        }
        return new GetRequest(url, tag, params, headers, id).build();
    }

    private String appendParams(String url, Map<String, Object> params) {
        if (url == null || params == null || params.isEmpty()) {
            return url;
        }

        Set<String> keys = params.keySet();
        Iterator<String> iterator = keys.iterator();

        // 将参数拼接到Url后面
        StringBuffer stringBuffer = new StringBuffer(url);
        stringBuffer.append("?");
        while (iterator.hasNext()) {
            String key = iterator.next();
            stringBuffer.append(key);
            stringBuffer.append("=");
            stringBuffer.append(params.get(key));
            stringBuffer.append("&");
        }
        url = stringBuffer.toString().substring(0, stringBuffer.length() - 1);

        Uri.Builder builder = Uri.parse(url).buildUpon();
        while (iterator.hasNext()) {
            String key = iterator.next();
            builder.appendQueryParameter(key, String.valueOf(params.get(key)));
        }

        return builder.build().toString();
    }

    @Override
    public OkHttpRequestBuilder params(Map<String, Object> params) {
        this.params = params;
        return this;
    }

    @Override
    public OkHttpRequestBuilder addParams(String key, Object value) {
        if (this.params == null) {
            params = new LinkedHashMap<>();
        }
        params.put(key, value);
        return this;
    }

}
